#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>

#define LOCAL_SERVER_PORT 7777
#define MAX_MSG 50

int main(int argc, char* argv[])
{
	int sd, rc, n, cliLen;
	struct sockaddr_in cliAddr, servAddr;
	char msg[MAX_MSG];

	sd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sd<0)
	{
		printf("%s: cannot open socket \n", argv[0]);
		exit(1);
	}

	servAddr.sin_family=AF_INET;
	servAddr.sin_addr.s_addr=htonl(INADDR_ANY);
	servAddr.sin_port=htons(LOCAL_SERVER_PORT);
	rc=bind(sd, (struct sockaddr*)&servAddr, sizeof(servAddr));
	if(rc<0)
	{
		printf("%s: cannot bind port number %d \n", argv[0], LOCAL_SERVER_PORT);
		exit(1);
	}

	while(1)
	{
		memset(msg, 0x0, MAX_MSG);
		cliLen = sizeof(cliAddr);
		n = recvfrom(sd, msg, MAX_MSG, 0, (struct sockaddr*)&cliAddr, &cliLen);
		if(n < 0)
		{
			printf("%s: cannnot receive data \n", argv[0]);
			continue;
		}
		printf("%s: from %s:UDP %u : %s\n", argv[0], inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port), msg);    
	}
	return 0;
}
